#include "mystdio.h"


FILE_* fopen_(const char* path_name,const char* mode){
  int flags = 0;//封装open的flags
  int defaultMode = 0666;//封装open的mode，默认是666
  if(strcmp(mode,"r") == 0){
    flags |= O_RDONLY;//只读
  }else if(strcmp(mode,"w")==0){
    flags |= (O_WRONLY | O_CREAT | O_TRUNC);
  }else if(strcmp(mode,"a")==0){
    flags |= (O_WRONLY | O_CREAT | O_APPEND);
  }else{

  }
  int fd = 0;//封装open的返回值，最后存在file结构体中
  if(flags & O_RDONLY) fd = open(path_name,flags);
  else fd = open(path_name,flags,defaultMode);
  if(fd < 0){
    const char* err = strerror(errno);
    write(2,err,strlen(err));
    return NULL;
  }

  //初始化缓冲区,也就是fopen()
  FILE_* fp = (FILE_*)malloc(sizeof(FILE_));//为返回值开空间
  assert(fp);
  fp->flags = SYNC_LINE; // 默认设置为行刷新
  fp->fileno = fd;
  fp->cap = SIZE;
  fp->size = 0;
  memset(fp->buffer,0,SIZE);
   
  return fp;
  
}

void fflush_(FILE_* fp){
  if(fp->size>0) write(fp->fileno,fp->buffer,fp->size);
  fsync(fp->fileno); //将数据，强制要求os进行外设刷新
  fp->size = 0;
}
void fwrite_(const void* ptr,int num,FILE_* fp){
  //1:写到缓冲区中(也可以理解为拷贝到缓冲区)
   memcpy(fp->buffer+fp->size,ptr,num);
   fp->size+=num;

   //2:判断是否刷新
   if(fp->flags & SYNC_NOW){
     write(fp->fileno,fp->buffer,fp->size);
     fp->size = 0;
   }else if(fp->flags & SYNC_FULL){
     if(fp->size == fp->cap){
       write(fp->fileno,fp->buffer,fp->size);
       fp->size =0;
     }else if(fp->flags & SYNC_LINE){
       if(fp->buffer[fp->size-1] == '\n'){
         write(fp->fileno,fp->buffer,fp->size);
         fp->size = 0;
       }
     }else{
        


     }
   }

}
void fclose_(FILE_* fp){
  fflush_(fp);//关闭文件会强制刷新缓冲区
  close(fp->fileno);//调用系统接口来关闭文件

}


